package com.imooc.controller;

import com.imooc.dto.OrderDTO;
import com.imooc.enums.ResultEnum;
import com.imooc.exception.SellException;
import com.imooc.service.OrderService;
import com.imooc.service.PayService;
import com.lly835.bestpay.model.PayResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;

/**
 * FileName: PayController.java
 * Description: 微信支付
 *
 * @author HuangRI(874668739 @ qq.com)
 * @version 1.0
 * @date 2020/12/28
 */
@Controller
@RequestMapping("/pay")
public class PayController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private PayService payService;

    /**
     * 向微信创建微信预付单并返回给客户支付
     * @param orderId
     * @param returnUrl
     * @param model
     * @return
     */
    @GetMapping("/create")
    public ModelAndView create(@RequestParam(value = "orderId", required = false) String orderId,
                         @RequestParam(value = "returnUrl", required = false) String returnUrl,
                               Map<String, Object> model) {
        // 1、查询订单
        OrderDTO orderDTO = this.orderService.findOne(orderId);
        if (null == orderDTO) {
            throw new SellException(ResultEnum.ORDER_NOT_EXIST);
        }

        PayResponse payResponse = this.payService.create(orderDTO);
        model.put("payResponse", payResponse);
        model.put("returnUrl", returnUrl);
        return new ModelAndView("/pay/create", model);
    }

    /**
     * 微信支付后给微信异步通知的接口
     * @param notifyData
     */
    @PostMapping("/notify")
    public ModelAndView notify(@RequestBody String notifyData) {
        // 1、接受微信异步通知
        this.payService.notify(notifyData);

        // 2、通知微信我们已经处理了
        // 见：https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_7&index=8
        return new ModelAndView("/pay/success");
    }
}
